<template>
  <div class="couple-container">
    <div class="header">
      <!--      <baidu-map id="allmap" @ready="mapReady">-->
      <!--        <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>-->
      <!--      </baidu-map>-->
      <div class="top">
        <p v-for="(item,index) in sentenceList" :key="index">{{ item ?? '我们的故事，开始了' }}</p>
      </div>
      <div class="weather">
        <img :src="weatherImg" alt="weather">
        <div>{{ weatherText }}</div>
        <div class="switch-wrap">
          <span v-if="userInfo.sex">
            <svg-icon v-show="!userInfo.sex" icon-class='lifu' width="22px" height="22px"
                      style="margin-top: -5px" class="genderIcon"/>
            <svg-icon v-show="userInfo.sex" icon-class='hunsha' width="22px" height="22px"
                      style="margin-top: -5px" class="genderIcon"/>
          </span>
          <van-switch
            :value="checked"
            @input="onInput"
            size="18px"
            active-color="#ac92eb"
            inactive-color="#ec87c0"
          />
          <span v-if="loverInfo">
            <svg-icon v-show="!loverInfo.sex" icon-class='lifu' width="22px" height="22px"
                      style="margin-top: -5px" class="genderIcon"/>
            <svg-icon v-show="loverInfo.sex" icon-class='hunsha' width="22px" height="22px"
                      style="margin-top: -5px" class="genderIcon"/>
          </span>
        </div>
      </div>
    </div>

    <!-- 未绑定情侣板块 -->
    <div class="offline" v-if="!userInfo.lover_id">
      <van-dialog
        v-model="isDialogShow"
        title="Have a crush"
        show-cancel-button
        @confirm="loverVerify"
        confirm-button-color="#ac92eb"
        className="offDialog"
      >
        <van-field v-model="loverTel" type="tel" label="TA's tel"/>
      </van-dialog>
      <div class="bind-box">
        <van-button type="default" @click="isDialogShow=true">
          绑定关系
          <template #icon>
            <svg-icon icon-class='xin-qinglv' width="18px" height="18px" class="icon"/>
          </template>
        </van-button>
        <svg-icon icon-class="offlineBg" width="100%" height="40vh" class="icon"/>
        <span>不会吧不会吧
          <br>不会有人没有女朋友就下载情侣app吧</span>
        <HeartIndex :numArr=[1,2,3,4]></HeartIndex>
      </div>

    </div>

    <!-- 已登录板块 -->
    <div class="online" v-else>
      <div class="count">
        我们已经在一起
        <div class="countNum">
          <div v-if="userInfo.together">
            {{ daysSince }}
          </div>
          <van-button type="default" @click="isTogetherShow=true" class="recordBtn" v-if="!userInfo.together">
            立即记录！
            <template #icon>
              <svg-icon icon-class='xin-qinglv' width="18px" height="18px" class="icon"/>
            </template>
          </van-button>
        </div>
        <div>天</div>
      </div>
      <van-dialog
        v-model="isTogetherShow"
        title="那天，我们在一起了"
        show-cancel-button
        @confirm="submitTime"
        confirm-button-color="#ac92eb"
        className="togetherDialog"
      >
        <van-field
          readonly
          clickable
          name="datetimePicker"
          :value="togetherValue"
          label="Crush Day:"
          placeholder="点击选择时间"
          @click="showPicker = true"
        />
      </van-dialog>
      <van-popup v-model="showPicker" position="bottom">
        <van-datetime-picker
          type="date"
          :min-date="minDate"
          :max-date="maxDate"
          v-model="maxDate"
          @confirm="selectedDate"
          @cancel="showPicker = false"
        />
      </van-popup>
      <!-- 用户信息区 -->
      <div class="base-info">
        <div class="info">
          <van-image
            class="avatar"
            round
            :src="userInfo.user_pic ?? require('@/assets/icons/girl.png')"
          />
          <div class="uName">{{ userInfo.username }}</div>
        </div>
        <HeartIndex :numArr=[1]></HeartIndex>
        <div class="info">
          <van-image
            class="loveAvatar"
            round
            :src="loverInfo.user_pic ?? require('@/assets/icons/boy.png')"
          />
          <div class="uName">{{ loverInfo.username }}</div>
        </div>
      </div>
      <!-- 四个选项 -->
      <van-grid :column-num="4">
        <van-grid-item text="梵高再现" @click="$router.push({ path: '/puzzle' })">
          <template #icon>
            <svg-icon style="margin-bottom: 3px;" icon-class='yizhipintu' width="30px" height="30px" class="icon"/>
          </template>
        </van-grid-item>
        <van-grid-item text="名字匹配" @click="$router.push({ path: '/match' })">
          <template #icon>
            <svg-icon style="margin-bottom: 3px;" icon-class='pipei' width="30px" height="30px" class="icon"/>
          </template>
        </van-grid-item>
        <van-grid-item text="星座运势" @click="$router.push({ path: '/luck' })">
          <template #icon>
            <svg-icon style="margin-bottom: 3px;" icon-class='xingzuo' width="30px" height="30px" class="icon"/>
          </template>
        </van-grid-item>
        <van-grid-item text="生日性格" @click="$router.push({ path: '/character' })">
          <template #icon>
            <svg-icon style="margin-bottom: 3px;" icon-class='xin-dangao' width="30px" height="30px" class="icon"/>
          </template>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>

<script>
import { getUserInfoAPI, postUserLoverIdAPI, updateUserProfileAPI } from '@/api'
import HeartIndex from './components/heart.vue'
import dayjs from 'dayjs'

export default {
  name: 'QaIndex',
  components: {
    HeartIndex
  },
  data () {
    return {
      userInfo: {},
      loginOutShow: false,
      infoWindowShow: false,
      longitude: '',
      latitude: '',
      weatherText: '',
      weatherImg: '',
      sentenceList: [],
      isDialogShow: false,
      loverTel: '',
      loverInfo: [],
      time: new Date(),
      checked: false,
      place: '',
      isTogetherShow: false,
      showPicker: false,
      togetherValue: '',
      minDate: new Date(1945, 0, 1),
      maxDate: new Date(),
      dayNum: ''
    }
  },
  computed: {
    daysSince () {
      return dayjs().diff(dayjs(this.userInfo.together), 'day')
    }
  },
  created () {
    // this.weatherText = 'test / test℃'
    // this.weatherImg = require('@/assets/weather/0@2x.png')
    // 进入个人中心页面时，就要请求数据（只有登录时触发）
    if (this.$store.state.user) {
      // 请求接口
      this.loadUserInfo()
      this.loveSentence()
      this.getWea('上海市')
      this.getPlaceIp()
    }
  },
  methods: {
    // 请求用户信息
    async loadUserInfo () {
      try {
        const res = await getUserInfoAPI()
        console.log(res)
        if (res.data.message === 'jwt expired') {
          this.loginOutShow = true
          return
        }
        this.userInfo = res.data.data
        this.loverInfo = res.data.loverData

        if (!this.userInfo.signature) {
          this.userInfo.signature = '快来创造独属于你们的恋爱宣言吧！'
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 地图初始化
    mapReady ({ BMap, map }) {
      this.point = new BMap.Point(113.27, 23.13) // 选择一个经纬度作为中心点
      map.centerAndZoom(this.point, 12) // 设置地图中心点和缩放级别
      this.map = map
      const localcity = new BMap.LocalCity()
      localcity.get(e => {
        console.log(e)
      })
    },
    loveSentence () {
      this.sentenceList = '你有打火机吗？没有啊，那你是怎么点燃我的心的？'.split(/[，；。 ]/)
      // fetch('https://apis.tianapi.com/saylove/index?key=c11a19c8088cd1833a55587b1eb8bb87')
      //   .then(response => response.json())
      //   .then(data => {
      //     const str = data.result.content
      //     this.sentenceList = str.split(/[，；。 ]/)
      //     console.log(this.sentenceList)
      //   })
      //   .catch(error => console.error(error))
    },
    async loverVerify () {
      try {
        const res = await postUserLoverIdAPI({
          loverTel: this.loverTel
        })
        console.log(res)
        this.loverTel = ''
        if (res.data.status === 0) {
          this.$toast.success('绑定关系成功')
        }
      } catch (error) {
        console.log(error)
        this.$toast.fail('绑定关系失败')
      }
    },
    onInput (checked) {
      if (!this.checked) {
        this.getWea(this.loverInfo.area ? this.loverInfo.area.substring(0, 2) : '北京')
      }
      if (this.checked) {
        this.getWea(this.place)
      }
      this.checked = checked
    },
    selectedDate (value) {
      this.togetherValue = dayjs(value).format('YYYY-MM-DD')
      this.showPicker = false
      console.log(this.togetherValue)
    },
    async submitTime () {
      try {
        await updateUserProfileAPI({
          together: this.togetherValue
        })
        await this.loadUserInfo()
        this.$toast.success('修改成功')
      } catch (error) {
        console.log(error)
        this.$toast.fail('修改失败')
      }
    },
    getWea (area) {
      // this.weatherText = 'test / test℃'
      // this.weatherImg = require('@/assets/weather/0@2x.png')
      fetch(`https://api.seniverse.com/v3/weather/now.json?key=S5wXMDL5ZQzBYrs4Z&location=${area}&language=zh-Hans&unit=c`)
        .then(response => response.json())
        .then(data => {
          console.log(data.results[0].now)
          this.weatherText = `${data.results[0].now.text} / ${data.results[0].now.temperature}℃`
          this.weatherImg = require(`@/assets/weather/${data.results[0].now.code}@2x.png`)
        })
        .catch(error => console.error(error))
    },
    getPlaceIp () {
      fetch('https://www.mxnzp.com/api/ip/self?app_id=pbimqfqkl0qazftk&app_secret=ZndGVnZEZ3NyYkpsUHQxRUM4YzBrZz09')
        .then(response => response.json())
        .then(data => {
          this.place = data.data.city
          console.log(data.data.city)
        })
        .catch(error => console.error(error))
    }
  }
}
</script>

<style scoped lang="less">
.couple-container {
  height: 100vh;
  width: 100%;
  padding-top: 20px;

  .header {
    position: relative;

    #allmap {
      position: absolute;
      display: none;
      width: 100%;
      height: 100px;
    }

    .top {
      padding: 10px 0px 5px;
      width: 52%;
      background-color: #fff;
      opacity: .85;
      transform: translateY(10px) rotateZ(-10deg);
      box-shadow: 0 2px 10px 1px rgba(0, 0, 0, 0.2);
      border-bottom-left-radius: 40px 500px;
      border-bottom-right-radius: 500px 30px;
      border-top-right-radius: 5px 100px;
      background: repeating-linear-gradient(top, #fcf59b, #fcf59b 29px, #81cbbc 30px);

      &:before {
        background: url("@/assets/note.png") no-repeat;
        background-size: cover;
        height: 25px;
        width: 35px;
        content: '';
        position: absolute;
        top: -11px;
        left: 40%;
      }

      p {
        font-size: 12px;
        margin: 10px 10px 10px 30px;
      }
    }

    .weather {
      position: absolute;
      top: 0;
      right: 20px;
      font-size: 15px;
      text-align: center;

      img {
        width: 40px;
        height: 40px;
      }

      .switch-wrap {
        .van-switch {
          margin-top: 8px;
          width: 3.5em;
          height: 0.5em;

          ::v-deep .van-switch__node {
            width: 0.8em;
            height: 0.8em;
            top: -30%;

          }

          ::v-deep.van-switch--on .van-switch__node {
            transform: translateX(2.8em);

          }
        }
      }

    }
  }

  &:before {
    background: url("@/assets/main.webp") no-repeat;
    background-size: cover;
    height: 100vh;
    width: 100%;
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
    opacity: .5;
  }

  .offDialog, .togetherDialog {
    height: 200px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    ::v-deep .van-cell {
      font-size: 15px;
      height: 50px;
    }
  }

  .offline {

    .bind-box {
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      text-align: center;

      .van-button {
        width: 150px;
        position: absolute;
        opacity: .85;
        border-radius: 20px;
      }

      span {
        font-size: 16px;
        letter-spacing: 2px;
      }
    }

    .icon {
      text-align: center;
    }

  }

  .online {
    .count {
      position: absolute;
      top: 30%;
      left: 50%;
      transform: translateX(-50%);
      text-align: center;
      font-size: 16px;
      color: #ac92eb;
      font-weight: bolder;

      .countNum {
        color: #ec87c0;
        font-size: 48px;

        .recordBtn {
          width: 150px;
          opacity: .85;
          border-radius: 20px;
          margin-bottom: 20px;
        }
      }
    }

    .base-info {
      position: absolute;
      display: flex;
      margin-left: 20px;
      top: 66%;

      .info {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-left: 10px;

        .avatar, .loveAvatar {
          width: 40px;
          height: 40px;
          border: 2px solid #ffffff;
        }

        .uName {
          font-size: 12px;
        }
      }

      .hearts {
        width: 20px;
        height: 10px;
        margin: 20px;
      }
    }

    // 样式穿透 - 第三方的组件样式可能会影响不到
    ::v-deep .van-grid {
      position: fixed;
      width: 95%;
      bottom: 10vh;
      padding: 0 10px;
      left: 50%;
      transform: translateX(-50%);

      &::after, &::before {
        border: none;
      }

      .van-grid-item {

        .van-grid-item__content {
          background-color: rgba(255, 255, 255, .5);
          margin: 5px;
          border-radius: 10px;

          &::after {
            border: none;
          }
        }
      }

    }
  }
}
</style>
